#ifndef UDPCLIENT_H
#define UDPCLIENT_H

// standard lib
#include <string>

// linux socket
#include <netinet/in.h>
#include <unistd.h>

// headfile
#include "PeerBase.h"

using namespace std;

static pthread_mutex_t peerListLock;
class UDPClient: public PeerBase
{
	private:
		// udp client
		int udp_fd;
		struct sockaddr_in udp_client_addr;
		int udpPort;
		int on;

		void Error(const char*);

		static void* RecvMsg(void*);
		void HandleRecvMsg(sockaddr* fromaddr, int addr_len);

		bool msgAck;
		bool login;
		bool userList;
		in_addr_t udp_server_ip;

		PEER_INFO peer; // client info
		
	
	public:
		pthread_t send_tid, recv_tid; // one thread for send and one for recv
		PeerList* peerList;
		
		UDPClient(string udpPort) {
			this->udpPort = atoi(udpPort.c_str());
			this->on = 1;
			peerListLock = PTHREAD_MUTEX_INITIALIZER;
			pthread_mutex_init(&peerListLock, NULL);
			this->peerList = new PeerList();
		}
		int InitUDPClient();

		bool Login(char* username, char* server_ip);
		void Logout();

		bool GetPeerList();

		bool SendText(char* username, char* text, int text_len);

		void onRecv(char* username, char* data, char* data_len);

		void Stop() {
			close(udp_fd);
		};

		~UDPClient() {
			Logout();
			Stop();
			pthread_mutex_destroy(&peerListLock);
			delete peerList;
		}
};


#endif
